﻿using System;
using System.Collections.ObjectModel;
using System.Windows.Forms;
using System.Drawing;
using System.Text;
using System.IO;
using System.Xml;

namespace nToDo
{
    public partial class MainUI : Form
    {
        private bool toolbar = false;
        private bool statusbar = false;
        private DateTime currentDay = DateTime.Now;
        public MainUI()
        {
            InitializeComponent();
            this.mainStatus.Text = "Welcome to nToDo";
            this.RefreshTasks();
            this.WindowResize();
        }

        private void addNewTaskButton_Click(object sender, EventArgs e)
        {
            this.AddNewTask();
        }

        private void AddNewTask()
        {
            AddNewTaskUI addnewTasks = new AddNewTaskUI(this.currentDay);
            addnewTasks.onEventAdded += new EventHandler(addnewTasks_onEventAdded);
            addnewTasks.ShowDialog(this);
        }

        private void EditTask(string TaskId)
        {
            AddNewTaskUI addnewTasks = new AddNewTaskUI(TaskId);
            addnewTasks.onEventAdded += new EventHandler(addnewTasks_onEventAdded);
            addnewTasks.ShowDialog(this);
        }

        void addnewTasks_onEventAdded(object sender, EventArgs e)
        {
            this.RefreshTasks();
        }

        private void markAsDoneButton_Click(object sender, EventArgs e)
        {
            this.markTaskDone();
        }

        private void markTaskDone()
        {
            if (this.listTasks.SelectedItems != null && this.listTasks.SelectedItems.Count >= 1)
            {
                DataAccess.GetInstance().MarkAsDone(this.listTasks.SelectedItems[0].Tag.ToString());
                this.RefreshTasks();
            }
        }

        private void removeTaskButton_Click(object sender, EventArgs e)
        {
            this.removeTask();
        }

        private void removeTask()
        {
            if (this.listTasks.SelectedItems != null && this.listTasks.SelectedItems.Count >= 1)
            {
                if (MessageBox.Show("Are you sure you want to delete this task?", Properties.Resources.ApplicationName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    DataAccess.GetInstance().RemoveTask(this.listTasks.SelectedItems[0].Tag.ToString());
                    this.RefreshTasks();
                }
            }
        }

        private void AboutButton_Click(object sender, EventArgs e)
        {
            this.ShowAbout();
        }

        private void ShowAbout()
        {
            AboutBox about = new AboutBox();
            if (this.WindowState == FormWindowState.Minimized)
            {
                about.StartPosition = FormStartPosition.CenterScreen;
            }
            about.ShowDialog(this);
        }
        private void RefreshTasks()
        {
            this.markAsDoneButton.Enabled = false;
            this.removeTaskButton.Enabled = false;
            this.Text = string.Format("nToDo - Tasks on {0}", this.currentDay.ToString("dd-MMM-yyyy"));
            this.listTasks.Items.Clear();
            Collection<Task> Tasks = DataAccess.GetInstance().GetTasks(currentDay);
            ListViewItem listItem;
            foreach (Task item in Tasks)
            {
                listItem = new ListViewItem(
                    new string[] { 
                        item.IsDone ? "Yes" : "No" , 
                        item.PriorityText, 
                        item.DueDate.ToString("dd-MMM-yyyy"),
                        item.Notes 
                    }, "", !item.IsDone ? Color.Red : Color.Black, Color.White, this.listTasks.Font);
                listItem.Tag = item.TaskId;
                this.listTasks.Items.Add(listItem);
            }
        }

        private void refreshButton_Click(object sender, EventArgs e)
        {
            this.RefreshTasks();
        }

        private void MainUI_Resize(object sender, EventArgs e)
        {
            this.WindowResize();
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ntodoTrayIcon.Visible = true;
                this.ShowInTaskbar = false;
            }
            else
            {
                this.ntodoTrayIcon.Visible = false;
                this.ShowInTaskbar = true;
            }
        }

        private void WindowResize()
        {
            if (this.WindowState != FormWindowState.Minimized)
            {
                this.Notes.Width = this.ClientSize.Width - 185;
            }
        }


        private void MainUI_FormClosing(object sender, FormClosingEventArgs e)
        {
            Properties.Settings.Default.Toolbar = this.toolbar;
            Properties.Settings.Default.StatusBar = this.statusbar;
            Properties.Settings.Default.Save();
        }

        private void CalendarButton_ButtonClick(object sender, EventArgs e)
        {
            this.GotoToday();
        }

        private void GotoToday()
        {
            this.currentDay = DateTime.Now;
            this.RefreshTasks();
        }

        private void previousDayButton_Click(object sender, EventArgs e)
        {
            this.currentDay = this.currentDay.AddDays(-1);
            this.RefreshTasks();
        }

        private void nextDayButton_Click(object sender, EventArgs e)
        {
            this.currentDay = this.currentDay.AddDays(1);
            this.RefreshTasks();
        }

        private void addNewTaskButton_MouseEnter(object sender, EventArgs e)
        {
            this.showStatus("Add a new Task");
        }

        private void showStatus(string status)
        {
            this.mainStatus.Text = status;
        }

        private void addNewTaskButton_MouseLeave(object sender, EventArgs e)
        {
            this.ResetStatus();
        }

        private void ResetStatus()
        {
            this.mainStatus.Text = "Welcome to nToDo";
        }

        private void markAsDoneButton_MouseLeave(object sender, EventArgs e)
        {
            this.ResetStatus();
        }

        private void markAsDoneButton_MouseEnter(object sender, EventArgs e)
        {
            this.showStatus("Mark a Task as Done");
        }

        private void CalendarButton_MouseEnter(object sender, EventArgs e)
        {
            this.showStatus("Show today's Task(s)");
        }

        private void CalendarButton_MouseLeave(object sender, EventArgs e)
        {
            this.ResetStatus();
        }

        private void previousDayButton_MouseEnter(object sender, EventArgs e)
        {
            this.showStatus("Show previous day's Task(s)");
        }

        private void previousDayButton_MouseLeave(object sender, EventArgs e)
        {
            this.ResetStatus();
        }

        private void nextDayButton_MouseLeave(object sender, EventArgs e)
        {
            this.ResetStatus();
        }

        private void nextDayButton_MouseEnter(object sender, EventArgs e)
        {
            this.showStatus("Show nextday's Task(s)");
        }

        private void refreshButton_MouseEnter(object sender, EventArgs e)
        {
            this.showStatus("Refresh Task(s)");
        }

        private void refreshButton_MouseLeave(object sender, EventArgs e)
        {
            this.ResetStatus();
        }

        private void removeTaskButton_MouseLeave(object sender, EventArgs e)
        {
            this.ResetStatus();
        }

        private void removeTaskButton_MouseEnter(object sender, EventArgs e)
        {
            this.showStatus("Remove a task");
        }

        private void AboutButton_MouseEnter(object sender, EventArgs e)
        {
            this.showStatus("About this application");
        }

        private void AboutButton_MouseLeave(object sender, EventArgs e)
        {
            this.ResetStatus();
        }

        private void MainUI_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                this.removeTask();
            }
            else if (e.KeyCode == Keys.F5)
            {
                this.RefreshTasks();
            }
            else if (e.KeyCode == Keys.N && e.Control)
            {
                this.AddNewTask();
            }
            else if (e.Control && e.KeyCode == Keys.Home)
            {
                this.GotoToday();
            }
            else if (e.Control && e.KeyCode == Keys.E)
            {
                this.ExportAsXml();
            }
            else if (e.Control && e.KeyCode == Keys.I)
            {
                this.ImportAsXml();
            }
        }

        private void gotoDayButton_Click(object sender, EventArgs e)
        {
            GotoUI gotoUi = new GotoUI(this.currentDay);
            gotoUi.onDateChanged += new DateRangeEventHandler(gotoUi_onDateChanged);
            gotoUi.ShowDialog(this);
        }

        void gotoUi_onDateChanged(object sender, DateRangeEventArgs e)
        {
            this.currentDay = e.Start;
            this.RefreshTasks();
        }

        private void gotoDayButton_MouseEnter(object sender, EventArgs e)
        {
            this.showStatus("Goto specific Date");
        }

        private void gotoDayButton_MouseLeave(object sender, EventArgs e)
        {
            this.ResetStatus();
        }

        private void listTasks_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            this.markAsDoneButton.Enabled = e.Item.SubItems[0].Text.Equals("No", StringComparison.CurrentCultureIgnoreCase);
            this.removeTaskButton.Enabled = e.IsSelected;
        }

        private void listTasks_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewItem item = this.listTasks.GetItemAt(e.X, e.Y);
            if (item != null && item.SubItems != null)
            {
                if (item.SubItems[0].Text.Equals("No", StringComparison.CurrentCultureIgnoreCase))
                {
                    this.EditTask(item.Tag.ToString());
                }
                else
                {
                    MessageBox.Show("This task is completed. You cannot edit a completed task", Properties.Resources.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private void ExportAsXml()
        {
            string appName = Properties.Resources.ApplicationName;

            Collection<Task> Tasks = DataAccess.GetInstance().GetTasks(currentDay);

            using (SaveFileDialog dlg = new SaveFileDialog())
            {
                dlg.AddExtension = true;
                dlg.CheckPathExists = true;
                dlg.DefaultExt = "XML";
                dlg.Filter = "Xml Files|*.xml";
                dlg.FileName = string.Format("Report_{0}", currentDay.ToString("dd_MMM_yyyy"));
                dlg.FilterIndex = 0;
                dlg.OverwritePrompt = true;
                dlg.ValidateNames = true;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    Tasks.GenerateXml(dlg.FileName);
                }
            }
        }

        private void ImportAsXml()
        {
            string appName = Properties.Resources.ApplicationName;

            Collection<Task> Tasks;

            using (OpenFileDialog dlg = new OpenFileDialog())
            {
                dlg.AddExtension = true;
                dlg.CheckPathExists = true;
                dlg.DefaultExt = "XML";
                dlg.Filter = "Xml Files|*.xml";
                dlg.FilterIndex = 0;
                dlg.ValidateNames = true;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    XmlDocument xDoc = new XmlDocument();
                    Tasks = xDoc.GenerateTasks(dlg.FileName);
                    foreach (Task item in Tasks)
                    {
                        DataAccess.GetInstance().AddTask(item);
                    }
                }
                this.RefreshTasks();
            }
        }

        private void MainUI_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            this.ShowTasks();
        }

        private void mniExitntodo_Click(object sender, EventArgs e)
        {
            this.ntodoTrayIcon.Dispose();
            this.Close();
        }

        private void mnishowntodo_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
        }

        private void mniAbout_Click(object sender, EventArgs e)
        {
            this.ShowAbout();
        }

        private void mniShowTasks_Click(object sender, EventArgs e)
        {
            this.ShowTasks();
        }

        private void ShowTasks()
        {
            StringBuilder html = new StringBuilder();
            Collection<Task> Tasks = DataAccess.GetInstance().GetTasks(currentDay);
            foreach (Task item in Tasks)
            {
                html.AppendLine("* " + item.Notes);
            }
            if (html.Length >= 1)
            {
                string title = string.Format("Tasks on {0}", currentDay.ToString("dd-MMM-yyyy"));
                this.ntodoTrayIcon.ShowBalloonTip(1000, title, html.ToString(), ToolTipIcon.None);
            }
        }

        private void ntodoTrayIcon_BalloonTipClicked(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
        }

        private void ntodoTrayIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.ShowTasks();
        }

        private void settingsButton_Click(object sender, EventArgs e)
        {
            Settings settings = new Settings();
            settings.ShowDialog(this);
        }

        private void settingsButton_MouseEnter(object sender, EventArgs e)
        {
            this.showStatus("nToDo Settings");
        }

        private void settingsButton_MouseLeave(object sender, EventArgs e)
        {
            this.ResetStatus();
        }
    }
}
